package com.cheng.im.service.friendship.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.im.common.constants.SeqConstants;
import com.cheng.im.service.common.eunms.DelFlagEnum;
import com.cheng.im.service.common.eunms.FriendShipErrorCode;
import com.cheng.im.service.common.resp.CommonResult;
import com.cheng.im.service.friendship.mapper.ImFriendshipGroupMapper;
import com.cheng.im.service.friendship.service.ImFriendshipGroupMemberService;
import com.cheng.im.service.friendship.service.ImFriendshipGroupService;
import com.cheng.im.service.frienship.domain.ImFriendshipGroup;
import com.cheng.im.service.frienship.model.req.AddFriendShipGroupMemberReq;
import com.cheng.im.service.frienship.model.req.AddFriendShipGroupReq;
import com.cheng.im.service.frienship.model.req.DeleteFriendShipGroupReq;
import com.cheng.im.service.redis.seq.RedisSeq;
import com.cheng.im.service.redis.seq.WriteUserSeq;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author Cheng
* @description 针对表【im_friendship_group】的数据库操作Service实现
* @createDate 2024-12-17 15:04:33
*/
@DubboService
public class ImFriendshipGroupServiceImpl extends ServiceImpl<ImFriendshipGroupMapper, ImFriendshipGroup>
    implements ImFriendshipGroupService {

    @Resource
    private ImFriendshipGroupMemberService imFriendshipGroupMemberService;
    @Resource
    RedisSeq redisSeq;
    @Resource
    WriteUserSeq writeUserSeq;

    @Override
    @Transactional
    public CommonResult addGroup(AddFriendShipGroupReq req) {
        LambdaQueryWrapper<ImFriendshipGroup> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendshipGroup::getGroupName, req.getGroupName());
        query.eq(ImFriendshipGroup::getAppId, req.getAppId());
        query.eq(ImFriendshipGroup::getFromId, req.getFromId());
        query.eq(ImFriendshipGroup::getDelFlag, DelFlagEnum.NORMAL.getCode());

        ImFriendshipGroup entity = baseMapper.selectOne(query);

        if (entity != null) {
            return CommonResult.failed(FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_EXIST.getCode(),
                    FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_EXIST.getError());
        }

        //写入db
        ImFriendshipGroup insert = new ImFriendshipGroup();
        insert.setAppId(req.getAppId());
        insert.setCreateTime(System.currentTimeMillis());
        insert.setDelFlag(DelFlagEnum.NORMAL.getCode());
        insert.setGroupName(req.getGroupName());
        long seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP_GROUP);
        insert.setSequence(seq);
        insert.setFromId(req.getFromId());
        try {
            int insert1 = baseMapper.insert(insert);

            if (insert1 != 1) {
                return CommonResult.failed(FriendShipErrorCode.FRIEND_SHIP_GROUP_CREATE_ERROR.getCode(),
                        FriendShipErrorCode.FRIEND_SHIP_GROUP_CREATE_ERROR.getError());
            }
            if (insert1 == 1 && CollectionUtil.isNotEmpty(req.getToIds())) {
                AddFriendShipGroupMemberReq addFriendShipGroupMemberReq = new AddFriendShipGroupMemberReq();
                addFriendShipGroupMemberReq.setFromId(req.getFromId());
                addFriendShipGroupMemberReq.setGroupName(req.getGroupName());
                addFriendShipGroupMemberReq.setToIds(req.getToIds());
                addFriendShipGroupMemberReq.setAppId(req.getAppId());
                imFriendshipGroupMemberService.addGroupMember(addFriendShipGroupMemberReq);
                return CommonResult.success();
            }
        } catch (DuplicateKeyException e) {
            e.getStackTrace();
            return CommonResult.failed(FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_EXIST.getCode(),
                    FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_EXIST.getError());
        }

        // todo: 通知
//        AddFriendGroupPack addFriendGropPack = new AddFriendGroupPack();
//        addFriendGropPack.setFromId(req.getFromId());
//        addFriendGropPack.setGroupName(req.getGroupName());
//        addFriendGropPack.setSequence(seq);
//        messageProducer.sendToUserExceptClient(req.getFromId(), FriendshipEventCommand.FRIEND_GROUP_ADD,
//                addFriendGropPack,new ClientInfo(req.getAppId(),req.getClientType(),req.getImei()));
//        //写入seq
        writeUserSeq.writeUserSeq(req.getAppId(), req.getFromId(), SeqConstants.FRIENDSHIP_GROUP, seq);

        return CommonResult.success();
    }

    @Override
    @Transactional
    public CommonResult deleteGroup(DeleteFriendShipGroupReq req) {
        for (String groupName : req.getGroupName()) {
            LambdaQueryWrapper<ImFriendshipGroup> query = new LambdaQueryWrapper<>();
            query.eq(ImFriendshipGroup::getGroupName, groupName);
            query.eq(ImFriendshipGroup::getAppId, req.getAppId());
            query.eq(ImFriendshipGroup::getFromId, req.getFromId());
            query.eq(ImFriendshipGroup::getDelFlag, DelFlagEnum.NORMAL.getCode());

            ImFriendshipGroup entity = baseMapper.selectOne(query);

            if (entity != null) {
                long seq = redisSeq.doGetSeq(req.getAppId() + ":" + SeqConstants.FRIENDSHIP_GROUP);
                ImFriendshipGroup update = new ImFriendshipGroup();
                update.setSequence(seq);
                update.setGroupId(entity.getGroupId());
                update.setDelFlag(DelFlagEnum.DELETE.getCode());
                baseMapper.updateById(update);
                imFriendshipGroupMemberService.clearGroupMember(entity.getGroupId());

                // todo: 通知
//                DeleteFriendGroupPack deleteFriendGroupPack = new DeleteFriendGroupPack();
//                deleteFriendGroupPack.setFromId(req.getFromId());
//                deleteFriendGroupPack.setGroupName(groupName);
//                deleteFriendGroupPack.setSequence(seq);
//                //TCP通知
//                messageProducer.sendToUserExceptClient(req.getFromId(), FriendshipEventCommand.FRIEND_GROUP_DELETE,
//                        deleteFriendGroupPack,new ClientInfo(req.getAppId(),req.getClientType(),req.getImei()));
//                //写入seq
                writeUserSeq.writeUserSeq(req.getAppId(), req.getFromId(), SeqConstants.FRIENDSHIP_GROUP, seq);

            }
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<ImFriendshipGroup> getGroup(String fromId, String groupName, String appId) {
        LambdaQueryWrapper<ImFriendshipGroup> query = new LambdaQueryWrapper<>();

        query.eq(ImFriendshipGroup::getGroupName, groupName);
        query.eq(ImFriendshipGroup::getAppId, appId);
        query.eq(ImFriendshipGroup::getFromId, fromId);
        query.eq(ImFriendshipGroup::getDelFlag, DelFlagEnum.NORMAL.getCode());

        ImFriendshipGroup entity = baseMapper.selectOne(query);
        if (entity == null) {
            return CommonResult.failed(FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_NOT_EXIST.getCode(),
                    FriendShipErrorCode.FRIEND_SHIP_GROUP_IS_NOT_EXIST.getError());
        }
        return CommonResult.success(entity);
    }

    @Override
    public Long updateSeq(String fromId, String groupName, String appId) {
        LambdaQueryWrapper<ImFriendshipGroup> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendshipGroup::getGroupName, groupName);
        query.eq(ImFriendshipGroup::getAppId, appId);
        query.eq(ImFriendshipGroup::getFromId, fromId);

        ImFriendshipGroup entity = baseMapper.selectOne(query);

        long seq = redisSeq.doGetSeq(appId + ":" + SeqConstants.FRIENDSHIP_GROUP);

        ImFriendshipGroup group = new ImFriendshipGroup();
        group.setGroupId(entity.getGroupId());
        group.setSequence(seq);
        baseMapper.updateById(group);

        return seq;
    }
}




